package com.njdf.servlet;

import com.njdf.entity.People;
import com.njdf.service.UserService;
import com.njdf.service.serviceImpl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class RegistServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String password2 = request.getParameter("password2");
        String verifyCode = request.getParameter("verifyCode");
        String img = (String)request.getSession().getAttribute("session_img");
        People people = new People(username, password, password2);
        PrintWriter out = response.getWriter();
        UserService userService = new UserServiceImpl();
        if (username == null || username == "" || password == null || password == "" || password2 == null || password2 == ""|| img == null || img == ""|| verifyCode == null || verifyCode == "") {
            out.print("注册失败，不能为空");
            response.setHeader("refresh", "3;" + request.getContextPath() + "/regist.jsp");
        } else {
            if (password.equals(password2)&&verifyCode.equalsIgnoreCase(img)) {
                Boolean b = userService.insert(people);
                if (!b) {
                    out.print("账户名重复，注册失败，请重新注册");
                    response.setHeader("refresh", "3;" + request.getContextPath() + "/regist.jsp");
                } else {
                    out.print("注册成功，3秒后跳转登录页面");
//                    List<People> peoples=new ArrayList<>();
//                    peoples= userService.queryAll();
//                    people=userService.queryByName(username);
//                    request.setAttribute("peoples",peoples);
//                    request.getSession().setAttribute("people",people);
//                    request.getRequestDispatcher("/success.jsp").forward(request, response);
                    response.setHeader("refresh", "3;" + request.getContextPath() + "/index.jsp");
                }
            } else {
                out.print("两次密码不一致，或验证码不能为空，请重新注册");
                response.setHeader("refresh", "2;" + request.getContextPath() + "/regist.jsp");
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
